<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Goods\Entity\GoodsInTag;
use Goods\Entity\GoodsTag;
use Goods\Form\GoodsTagForm;
use Goods\Service\GoodsInTagManager;
use Goods\Service\GoodsTagManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;

class GoodsTagController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $goodsTagManager;
    private $goodsInTagManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        GoodsTagManager $goodsTagManager,
        GoodsInTagManager $goodsInTagManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->goodsTagManager  = $goodsTagManager;
        $this->goodsInTagManager = $goodsInTagManager;
    }

    /**
     * 商品标签列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $tagList = $this->entityManager->getRepository(GoodsTag::class)->findAllGoodsTag();

        return ['tagList' => $tagList];
    }

    /**
     * 添加商品标签
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $form = new GoodsTagForm();
        $form->get('tagGroupId')->setValueOptions($this->goodsPlugin()->tagGroupOptions());

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                $this->goodsTagManager->addGoodsTag($data);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('商品标签 %s 添加成功!'), $data['tagName']), $this->translator->translate('商品标签'));

                return $this->redirect()->toRoute('goods-tag');
            }
        }
        $form->get('tagName')->setAttributes(['placeholder' => $this->translator->translate('可同时添加多个标签，一行一个')]);

        return ['form' => $form];
    }

    /**
     * 编辑商品标签
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $tagId = (int) $this->params()->fromRoute('id', -1);

        $tagInfo = $this->entityManager->getRepository(GoodsTag::class)->findOneByTagId($tagId);
        if($tagInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该标签不存在!'));
            return $this->redirect()->toRoute('goods-tag');
        }

        $form = new GoodsTagForm('edit');
        $form->get('tagGroupId')->setValueOptions($this->goodsPlugin()->tagGroupOptions());

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                $this->goodsTagManager->editGoodsTag($data, $tagInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('商品标签 %s 编辑成功!'), $data['tagName']), $this->translator->translate('商品标签'));

                return $this->redirect()->toRoute('goods-tag');
            }
        } else $form->setData($tagInfo->valuesArray());

        $query = $this->entityManager->getRepository(GoodsInTag::class)->findInTagGoods($tagId);
        $paginator  = $this->adminCommon()->shopPaginator($query, 1);

        return ['form' => $form, 'tagInfo' => $tagInfo, 'goodsList' => $paginator];
    }

    /**
     * 删除商品标签
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $tagId = (int) $this->params()->fromRoute('id', -1);
        $tagInfo = $this->entityManager->getRepository(GoodsTag::class)->findOneByTagId($tagId);
        if($tagInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该标签不存在!'));
            return $this->adminCommon()->toReferer();
        }

        $this->goodsTagManager->deleteGoodsTag($tagInfo);

        $this->getEventManager()->trigger('tag.delete.post', $this, [$tagId]);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('标签 %s 删除成功!'), $tagInfo->getTagName()), $this->translator->translate('商品标签'));

        return $this->adminCommon()->toReferer();
    }

    /**
     * 添加单个标签商品
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addTagGoodsAction()
    {
        $goodsId= (int) $this->params()->fromPost('goodsId', -1);
        $tagId  = (int) $this->params()->fromPost('tagId', -1);

        $goodsInfo  = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        $tagInfo    = $this->entityManager->getRepository(GoodsTag::class)->findOneByTagId($tagId);
        if($goodsInfo && $tagInfo) {
            $tagGoods = $this->entityManager->getRepository(GoodsInTag::class)->findOneBy(['goodsId' => $goodsId, 'tagId' => $tagId]);
            if ($tagGoods == null) {
                $addState = $this->goodsInTagManager->addOneGoodsInTag(['tagId' => $tagId, 'goodsId' => $goodsId, 'tagGoodsSort' => 255]);
                if($addState) {
                    return new JsonModel([
                        'state' => 'ok',
                        'result'=> [
                            'inTagId' => $addState->getInTagId(),
                            'goodsId' => $goodsId,
                            'goodsState' => Common::goodsState($this->translator)[$goodsInfo->getGoodsState()],
                            'goodsName' => $goodsInfo->getGoodsName()
                        ]
                    ]);
                }
            }
        }
        return new JsonModel(['state' => 'error']);
    }

    /**
     * 标签商品分页列表
     * @return ViewModel
     */
    public function ajaxTagGoodsAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $tagId  = (int) $this->params()->fromRoute('id', -1);
        $page   = (int) $this->params()->fromQuery('page', 1);

        $query = $this->entityManager->getRepository(GoodsInTag::class)->findInTagGoods($tagId);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return $view->setVariables(['tagId' => $tagId, 'goodsList' => $paginator]);
    }

    /**
     * 删除标签商品中的某一个商品
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteTagGoodsAction()
    {
        $inTagId = (int) $this->params()->fromRoute('id', -1);
        $inTagInfo = $this->entityManager->getRepository(GoodsInTag::class)->findOneByInTagId($inTagId);
        if($inTagInfo == null) return new JsonModel(['msg' => $this->translator->translate('该标签商品不存')]);
        $this->goodsInTagManager->deleteGoodsInTag($inTagInfo);
        return new JsonModel(['state' => 'ok']);
    }

    /**
     * 批量修改标签排序
     * @return mixed
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAllSortAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            if(!empty($data['tagSort'])) {
                $this->goodsTagManager->updateAllTagSort($data);

                $this->adminCommon()->addOperLog($this->translator->translate('批量排序处理成功!'), $this->translator->translate('商品标签'));
            }
        }

        return $this->adminCommon()->toReferer();
    }
}